package com.bitdf.txing.search.config;

import com.alibaba.fastjson.JSON;
import com.bitdf.txing.search.constant.EsConstant;
import com.bitdf.txing.search.to.GroupInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author Lizhiwei
 * @date 2023/9/9 10:24:30
 * 注释：
 */
@Slf4j
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Autowired
    RBloomFilter bloomFilter;
    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 在项目启动时设置好布隆过滤器
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("初始化布隆过滤器");
        //查询出es中的所有组团数据ids
        SearchRequest searchRequest = new SearchRequest(EsConstant.GROUP_INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery()).size(Integer.MAX_VALUE);
        sourceBuilder.trackTotalHits(true);
        searchRequest.source(sourceBuilder);
        // 指定返回字段
        String[] includeFields = new String[]{"id"};
        String[] exclude = new String[]{""};
        FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includeFields, exclude);
        sourceBuilder.fetchSource(fetchSourceContext);
        // 查询
        SearchResponse response = restHighLevelClient.search(searchRequest, TxElasticConfig.COMMON_OPTIONS);
        // 重新添加到布隆过滤器
        for (SearchHit hit : response.getHits()) {
            if (hit != null) {
                GroupInfoTo groupInfoTo = JSON.parseObject(hit.getSourceAsString(), GroupInfoTo.class);
                bloomFilter.add(groupInfoTo.getId());
            }
        }
        log.info("布隆过滤器 初始化完毕， 当前组团数： {}", bloomFilter.count());
    }
}
